<template>
  <div class="mine-container">
    <!-- 顶部用户信息区域 -->
    <div class="header">
      <div class="user-info">
        <van-image class="avatar" :src="avatarPlaceholder" round fit="cover" @click="handlePersonalDetail" />
        <div class="user-content">
          <div class="username">{{ username }}</div>
          <div class="stats">
            <div class="stat-item">
              <span class="stat-number">{{ checkinDays }}</span>
              <span class="stat-label">已连续打卡</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ bookkeepingDays }}</span>
              <span class="stat-label">记账总天数</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ recordCount }}</span>
              <span class="stat-label">记账总笔数</span>
            </div>
          </div>
        </div>
        <van-button 
          class="checkin-btn" 
          round 
          size="small"
          :disabled="hasCheckedInToday"
          @click="handleCheckin"
        >
          {{ hasCheckedInToday ? '已打卡' : '打卡' }}
        </van-button>
      </div>
    </div>

     <!-- 消息通知区域 -->
     <div class="notifications">
      <div class="notification-item" @click="goToMessages">
        <van-icon name="volume-o" class="notification-icon" />
        <div class="notification-content">
          <span v-if="unreadMessageCount > 0">您有 {{ unreadMessageCount }} 条消息</span>
          <span v-else class="no-message">暂无通知</span>
        </div>
        <van-icon name="arrow" class="more-icon" />
      </div>
    </div>

    <!-- 账户概览区域 -->
    <div class="account-overview" @click="goToOverview">
      <div class="section-header">
        <h3>账户概览</h3>
        <van-icon name="arrow" class="more-icon" @click="goToOverview" />
      </div>
      <div class="overview-stats">
        <div class="overview-item">
          <span class="overview-label">本月支出</span>
          <span class="overview-amount expense">¥{{ monthlyExpense.toFixed(2) }}</span>
        </div>
        <div class="overview-item">
          <span class="overview-label">本月收入</span>
          <span class="overview-amount income">¥{{ monthlyIncome.toFixed(2) }}</span>
        </div>
        <div class="overview-item">
          <span class="overview-label">结余</span>
          <span class="overview-amount balance">¥{{ balance.toFixed(2) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 功能列表区域 -->
    <div class="function-list">
      <van-cell icon="manager-o" title="账号设置" is-link @click="goToMineDetail" />
      <van-cell icon="balance-o" title="我的账本" is-link @click="goToLedger" />
      <van-cell icon="question-o" title="使用帮助" is-link @click="goToHelp" />
      <van-cell icon="edit" title="意见反馈" is-link @click="goToFeedback" />
      <van-cell icon="like-o" title="去应用市场给鲨鱼记账评分" is-link @click="goToRate" />
      <van-cell icon="info-o" title="关于鲨鱼记账V1.0.1" is-link @click="goToAbout" />
      <van-cell icon="info-o" title="退出登录" is-link @click="handleLogout" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserStats, checkin } from '@/api'
import { showToast, showConfirmDialog } from 'vant'
import { getToken, removeToken } from '@/utils/token'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 用户数据
const username = ref('未登录')
const checkinDays = ref('0')
const bookkeepingDays = ref('0')
const recordCount = ref('0')
const avatarPlaceholder = ref() // 实际项目中替换为真实头像
// 账户概览数据
const monthlyIncome = ref(0.00)
const monthlyExpense = ref(0.00)
const balance = ref(0.00)
// 未读消息数
const unreadMessageCount = ref(0)
// 打卡状态
const hasCheckedInToday = ref(false)

// 修改个人信息
const handlePersonalDetail = () => {
  // 检查用户是否已登录
  const token = getToken()
  if (!token) {
    console.log('用户未登录，使用默认数据')
    // 可以选择跳转到登录页
    router.push({ name: 'login' })
    // 或者显示提示
    showToast('请先登录')
    return
  }
  // 跳转到个人信息页面
  router.push({ name: 'mineDetail' })
}

// 获取用户统计数据
const fetchUserStats = async () => {
  // 检查是否已登录
  const token = getToken()
  if (!token) {
    console.log('用户未登录，使用默认数据')
    // 可以选择跳转到登录页
    router.push({ name: 'login' })
    // 或者显示提示
    showToast('请先登录')
    return
  }
  try {
    const data = await getUserStats()
    console.log('用户统计数据:', data)
    // 更新用户数据
    username.value = data.username || '用户' //用户名
    checkinDays.value = data.checkinDays || 0 // 连续打卡天数
    bookkeepingDays.value = data.bookkeepingDays || 0 // 记录天数
    recordCount.value = data.recordCount || 0 // 记录笔数
    // 更新账户概览数据
    monthlyIncome.value = data.monthlyIncome || 0 // 本月收入
    monthlyExpense.value = data.monthlyExpense || 0 // 本月支出
    balance.value = data.balance || 0 // 结余
    // 更新未读消息数
    unreadMessageCount.value = data.unreadMessageCount || 0 // 未读消息数
    // 更新今天是否已打卡的状态
    hasCheckedInToday.value = data.hasCheckedInToday || false // 今天是否已打卡
    // 更新头像
    if (data.avatar) {
      avatarPlaceholder.value = data.avatar // 头像
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
    showToast('获取数据失败，请稍后重试')
  }
}

// 打卡功能
const handleCheckin = async () => {
  if (hasCheckedInToday.value) {
    showToast('今天已经打卡过了')
    return
  }
  const token = getToken()
  if (!token) {
    showToast('请先登录')
    router.push({ name: 'login' })
    return
  }
  try {
    const data = await checkin()
    console.log('打卡结果:', data)
    
    if (data.alreadyChecked) {
      showToast(data.message || '今天已经打卡过了')
    } else {
      showToast('打卡成功！')
    }
    // 打卡请求完成后刷新用户统计数据，获取最新的打卡天数和状态
    await fetchUserStats()
  } catch (error) {
    console.error('打卡失败:', error)
    // 如果提示今天已打卡，更新状态并刷新数据
    if (error.message && error.message.includes('已经打卡')) {
      showToast('今天已经打卡过了')
      await fetchUserStats()
    } else {
      showToast('打卡失败，请稍后重试')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserStats()
})

// 页面跳转方法

// 跳转到个人信息页面
const goToMineDetail = () => router.push({ name: 'mineDetail' })

// 跳转到账户概览页面
const goToOverview = () => {
  router.push({ 
    name: 'accountOverview' 
  })
}
// 跳转到账本页面
const goToLedger = () => {
  router.push({ 
    name: 'ledger' 
  })
}
// 跳转到帮助页面
const goToHelp = () => {
  router.push({ 
    name: 'useHelp' 
  })
}
// 跳转到反馈页面
const goToFeedback = () => {
  router.push({ 
    name: 'feedback' 
  })
}
// 点击应用市场评分
const goToRate = () => {
  window.open('https://h5coml.vivo.com.cn/h5coml/appdetail_h5/browser_v2/index.html?appId=1903347&resource=301&source=7')
}
// 跳转到关于页面
const goToAbout = () => {
  router.push({ 
    name: 'aboutSharkBookkeeping' 
  })
}
// 跳转到消息页面
const goToMessages = () => {
  router.push({ 
    name: 'message' 
  })
}

// 退出登录
const handleLogout = async () => {
  try {
    await showConfirmDialog({
      title: '退出登录',
      message: '确定要退出登录吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      confirmButtonColor: '#FF6B6B',
    })
    // 用户确认退出
    // 清除token
    removeToken()
    // 清除用户store中的数据
    if (userStore && userStore.logout) {
      userStore.logout()
    }
    showToast('已退出登录')
    // 跳转到登录页
    router.push({ name: 'login' })
  } catch (error) {
    // 用户取消退出，不做任何操作
    console.log('用户取消退出登录')
  }
}
</script>

<style lang='scss' scoped>
.mine-container {
  min-height: 800px;
  background-color: #f5f5f5;

  /* 顶部用户信息区域 */
  .header {
    height: 160px;
    background-color: #FFD847;
    padding: 20px;
    border-radius: 0 0 40px 40px;

    .user-info {
      display: flex;
      align-items: flex-start;
      height: 100%;

      // 头像样式，确保不会被压缩
      .avatar {
        width: 60px;
        height: 60px;
        border: 2px solid white;
        flex-shrink: 0; // 防止被压缩
      }

      // 用户内容区域
      .user-content {
        margin-left: 15px;
        flex: 1;

        .username {
          padding-top: 20px;
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin-bottom: 10px;
        }

        // 统计数据区域
        .stats {
          width: 280px;
          padding-top: 20px;
          margin-left: -50px;
          display: flex;
          justify-content: space-between;

          .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;

            .stat-number {
              font-size: 19px;
              font-weight: bold;
              color: #333;
            }

            .stat-label {
              font-size: 11px;
              color: #666;
              margin-top: 2px;
            }
          }
        }
      }

      // 打卡按钮
      .checkin-btn {
        position: absolute;
        right: 0;
        margin: 20px 20px 0 0;
        background-color: white;
        color: #ff6600;
        font-size: 12px;
        padding: 4px 12px;
        margin-left: 10px;
        flex-shrink: 0; // 防止被压缩
        
        &:disabled {
          background-color: #f5f5f5;
          color: #999;
          cursor: not-allowed;
        }
      }
    }
  }

  /* 通用区域样式 */
  .account-overview,
  .recent-records {
    background-color: #fff;
    margin: 10px;
    border-radius: 6px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h3 {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin: 0;
      }

      .more-icon {
        color: #999;
        font-size: 14px;
      }
    }
  }

  /* 消息通知样式 */
  .notifications {
    background-color: #fff;
    margin: -20px 10px 10px 10px;
    border-radius: 6px;
    padding: 12px 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .notification-item {
      display: flex;
      align-items: center;

      .notification-icon {
        font-size: 18px;
        color: #ff9900;
        margin-right: 10px;
      }

      .notification-content {
        flex: 1;
        font-size: 14px;
        color: #666;
        
        .no-message {
          color: #999;
        }
      }

      .more-icon {
        color: #999;
        font-size: 14px;
      }
    }
  }

  /* 账户概览区域样式 */
  .account-overview {
    .overview-stats {
      display: flex;
      justify-content: space-between;
      text-align: center;

      .overview-item {
        flex: 1;

        .overview-label {
          font-size: 12px;
          color: #666;
          display: block;
          margin-bottom: 5px;
        }

        .overview-amount {
          font-size: 18px;
          font-weight: bold;
        }

        .expense {
          color: #ff6666;
        }

        .income {
          color: #52c41a;
        }

        .balance {
          color: #1890ff;
        }
      }
    }
  }

  /* 最近记账记录样式 */
  .recent-records {
    .record-list {
      .record-item {
        display: flex;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .record-icon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          font-weight: bold;
          color: white;
          margin-right: 12px;
        }

        .record-icon.expense {
          background-color: #ff6666;
        }

        .record-icon.income {
          background-color: #52c41a;
        }

        .record-info {
          flex: 1;

          .record-name {
            font-size: 15px;
            color: #333;
            margin-bottom: 4px;
          }

          .record-time {
            font-size: 12px;
            color: #999;
          }
        }

        .record-amount {
          font-size: 16px;
          font-weight: bold;
        }

        .record-amount.expense {
          color: #ff6666;
        }

        .record-amount.income {
          color: #52c41a;
        }
      }

      .no-records {
        text-align: center;
        padding: 20px 0;
        color: #999;
        font-size: 14px;
      }
    }
  }

  /* 功能列表区域 */
  .function-list {
    background-color: #fff;
    margin: 10px;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    :deep(.van-cell) {
      border-bottom: 1px solid #f5f5f5;
      height: 60px; /* 增加高度，默认是50px */
      font-size: 15px;
      color: #333;
      padding: 20px 16px; /* 增加内边距，默认是12px 16px */
      
      &:last-child {
        border-bottom: none;
      }
      
      .van-icon {
        font-size: 18px;
        margin-right: 10px;
        color: #e3b50e;
      }
    }
  }
}
</style>